package crp.core.department.domain.services;

import crp.core.department.domain.models.DepartmentEntity;
import crp.core.department.domain.repositories.DepartmentRepository;
import crp.core.shared.LifecycleStatus;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

@ApplicationScoped
public class DepartmentCreator {
    private final DepartmentRepository departmentRepository;

    @Inject
    public DepartmentCreator(DepartmentRepository departmentRepository) {
        this.departmentRepository = departmentRepository;
    }

    public DepartmentEntity upsert(String code, String name) {
        return departmentRepository.findByCode(code)
                .orElseGet(() -> {
                    DepartmentEntity department = new DepartmentEntity();
                    department.setCode(code);
                    department.setName(name);
                    department.setStatus(LifecycleStatus.ENABLED);
                    departmentRepository.persist(department);
                    return department;
                });
    }

}
